#include <assert.h>
#include <stdio.h>
#include <sysexits.h>
#include <string.h>
#include <unistd.h>

#include <xmlsec/app.h>
#include <xmlsec/dl.h>

#include "mcx.h"

void usage(int show) {
  fputs("Usage:\n", stderr);
  if(show & 1)
    fputs("\tmcx [-vv] balance\n", stderr);
  if(show & 2)
    fputs("\tmcx [-vv] history\n", stderr);
  exit(EX_USAGE);
}

void show_balance(gpointer key, gpointer value, gpointer data) {
  printf("%s: %s\n", (char *)key, (char *)value);
}

gint show_transaction(gpointer key, gpointer value, gpointer data) {
  struct mcx_transaction *t = value;

  printf("%s %1s%s %s (%d >> %d)\n", t->mt_time, t->mt_debit ? "-" : "",
	 t->mt_amount, t->mt_currency, t->mt_authority, t->mt_drawdown);
  return FALSE;
}

int main(int argc, char **argv) {
  xmlSecKeyPtr key;
  int ch;
  
  xmlInitParser();
  assert(!xmlSecInit());
#ifndef XMLSEC_NO_CRYPTO_DYNAMIC_LOADING
  assert(!xmlSecCryptoDLLoadLibrary("openssl"));
#endif
  assert(!xmlSecCryptoAppInit(NULL));
  assert(!xmlSecCryptoInit());

  while((ch = getopt(argc, argv, "v")) != -1) {
    switch(ch) {
    case 'v':
      mcx_debug_set(mcx_debug_get() + 1);
      break;
    case '?':
      usage(-1);
      break;
    }
  }
  
  if((argc - optind) < 1)
    usage(-1);

  key = mcx_loadkey(SYSCONFDIR "/key.rsa");
  if(!key) {
    fputs("No key found", stderr);
    exit(EX_NOINPUT);
  }

  if(!strcmp(argv[optind], "balance")) {
    GHashTable *balance;
    balance = mcx_balance(key);
    if(!balance) {
      fputs("Failed to retrieve balance.\n", stderr);
      exit(EX_SOFTWARE);
    }
    g_hash_table_foreach(balance, show_balance, NULL);
  } else if(!strcmp(argv[optind], "history")) {
    GTree *history;
    
    history = mcx_history(key);
    if(!history) {
      fputs("Failed to retrieve account history.\n", stderr);
      exit(EX_SOFTWARE);
    }
    g_tree_traverse(history, show_transaction, G_IN_ORDER, NULL);
  } else
    usage(-1);
  return 0;
}
